package com.siae.controller;



import com.siae.exce.BizException;
import com.siae.pojo.UploadFile;
import com.siae.pojo.vo.Result;
import com.siae.service.UploadFileService;
import com.siae.utils.AliyunOSSUtils;
import com.siae.utils.BizCode;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Tag(name = "UploadController",description = "文件上传")
public class UploadController {
    @Autowired
    private UploadFileService uploadFileService;
    @PostMapping
    public Result<String> upload(
            @RequestParam("file") MultipartFile multipartFile,
            @RequestParam("userId") String userId

    ){
        String fileName = multipartFile.getOriginalFilename();
        String fileType = multipartFile.getContentType();
        Long fileSize = multipartFile.getSize();
        UploadFile uploadFile = new UploadFile();
        try{
            // 使用JDK提供的UUID类，获取伪随机数串
            UUID uuid = UUID.randomUUID();
            // 获取原有文件名的扩展名
            String startstring = fileName.substring(0,fileName.lastIndexOf("."));
            String laststring = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            fileName = startstring + uuid.toString().substring(0, 8) + laststring;
            // 获取到上传的文件数据
            String filePath = AliyunOSSUtils.uploadFile(multipartFile.getInputStream(), fileName);
            uploadFile.setFileName(fileName);
            uploadFile.setFileType(fileType);
            uploadFile.setFileSize(fileSize / 1024 + "KB");
            uploadFile.setFilePath(filePath);
            uploadFile.setUserId(Integer.valueOf(userId));
            uploadFileService.addUploadFile(uploadFile);
            return Result.success(BizCode.SUCCESS,filePath);
        }catch (Exception e){
            throw new BizException(BizCode.FILE_UPLOAD_ERROR);
        }
    }
}
